package cn.itrip.auth.controller;

import cn.itrip.auth.exception.UserLoginFailedException;
import cn.itrip.auth.service.itripuser.ItripUserService;
import cn.itrip.auth.service.token.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.ErrorCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * LoginController class
 *
 * @author Administrator
 * @date 2021/7/2
 */
@Api(tags = "用户认证API")
@RestController
@RequestMapping("/api")
public class LoginController {
    private final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private ItripUserService userService;

    @Resource
    private TokenService tokenService;

    @ApiOperation(value = "用户登录", httpMethod = "POST", protocols = "http", produces = "application/json",
            response = Dto.class, notes = "根据用户名和密码进行统一认证")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", required = true, value = "用户名", name = "name", defaultValue = "itrip@163.com"),
            @ApiImplicitParam(paramType = "form", required = true, value = "密码", name = "password", defaultValue = "123456")
    })
    @RequestMapping(value = "dologin", method = RequestMethod.POST, produces = "application/json")
    public Dto<ItripTokenVO> dologin(@RequestParam String name,
                                     @RequestParam String password,
                                     @RequestHeader("user-agent") String userAgent) {
        // 数据的校验
        if(EmptyUtils.isEmpty(name) || EmptyUtils.isEmpty(password)) {
            return DtoUtil.returnFail("参数错误!请检查提交的参数名称或值是正确",
                    ErrorCode.AUTH_PARAMETER_ERROR);
        }
        // 登录,如果在登录的过程中,发现用户名或密码不正确,会抛出异常
        ItripUser user = null;
        try {
            user = userService.login(name, password);
        } catch (Exception e) {
            LOGGER.warn("{} 用户登录认证失败!", name, e);
            return DtoUtil.returnFail(e.getMessage(),
                    ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }
        // 生成token
        ItripTokenVO tokenVO = tokenService.generateToken(user, userAgent);
        // 保存token
        if(tokenService.save(tokenVO.getToken(), user)) {
            // 返回token信息
            return DtoUtil.returnDataSuccess(tokenVO);
        }

        return DtoUtil.returnFail("服务器内部错误", ErrorCode.SERVER_ERROR);
    }

}
